import * as THREE from 'three';
import { gsap } from "gsap";


// 提取材质到一个独立的对象，方便管理和复用
const materials = {
    baseMaterial: new THREE.MeshStandardMaterial({
        color: 0x444444, // 深灰色更接近金属
        metalness: 0.8,  // 高金属度
        roughness: 0.6,  // 较高粗糙度，磨砂感
    }),
};
// 定义动画变量
let doorAnimation, openDoorClip, openBackDoorLeft, openBackDoorRight;
// 定义动画函数


//初始化
export function init(scene){
    // 创建机柜的底部
    createCabinetBase(scene);
    // 创建机柜的顶部
    createCabinetTop(scene);
    // 创建机柜的侧面
    createCabinetSides(scene);
    let frontDoor = createCabinetFrontDoor(scene);
    let backDoor = createCabinetBackDoor(scene);
    createAnimation(frontDoor, backDoor.leftDoor, backDoor.rightDoor);
}


// 创建机柜不用修改的底部，顶部，侧面
export function createCabinetBase(scene) {
  const geometry = new THREE.BoxGeometry(0.6,  0.05, 0.64);
  const base = new THREE.Mesh(geometry,  materials.baseMaterial);
  base.position.y = -0.05; // 调整位置
  scene.add(base);
}
export function createCabinetTop(scene) {
  const geometry = new THREE.BoxGeometry(0.6, 0.05,  0.64);
  const top = new THREE.Mesh(geometry, materials.baseMaterial);
  top.position.y = 1.95; // 调整位置
  scene.add(top);
}

export function createCabinetSides(scene) {
  const geometry = new THREE.BoxGeometry(0.04, 2, 0.6);
  const material = materials.baseMaterial;
  // 左侧面
  const leftSide = new THREE.Mesh(geometry, material);
  leftSide.position.set(-0.28, 0.95, 0); // 调整位置
  scene.add(leftSide);
  // 右侧面
  const rightSide = new THREE.Mesh(geometry, material);
  rightSide.position.set(0.28, 0.95, 0); // 调整位置
  scene.add(rightSide);
}   

/**
 * 绘制前门
 * 门的高度和机柜高度一致，z正方向为前面，门的中间是透明玻璃，还有门把手
 */
export function createCabinetFrontDoor(scene) {
    // 创建一个组来包含前门的所有部分
    const doorGroup = new THREE.Group();

    // 门的整体尺寸
    const doorWidth = 0.04;
    const doorHeight = 2;
    const doorDepth = 0.6;

    // 门框（上下边框+左右边框）
    const frameMaterial = materials.baseMaterial;
    const frameThickness = 0.04;

    // 上边框
    const topFrameGeo = new THREE.BoxGeometry(doorWidth, frameThickness, doorDepth);
    const topFrame = new THREE.Mesh(topFrameGeo, frameMaterial);
    topFrame.position.set(0, 1 - frameThickness / 2, 0);
    doorGroup.add(topFrame);

    // 下边框
    const bottomFrameGeo = new THREE.BoxGeometry(doorWidth, frameThickness, doorDepth);
    const bottomFrame = new THREE.Mesh(bottomFrameGeo, frameMaterial);
    bottomFrame.position.set(0, -doorHeight / 2 + 0.05, 0);
    doorGroup.add(bottomFrame);

    // 左边框
    const leftFrameGeo = new THREE.BoxGeometry(doorWidth, doorHeight - 2 * frameThickness, frameThickness);
    const leftFrame = new THREE.Mesh(leftFrameGeo, frameMaterial);
    leftFrame.position.set(0, 1 - doorHeight / 2, -doorDepth / 2 + frameThickness / 2);
    doorGroup.add(leftFrame);

    // 右边框
    const rightFrameGeo = new THREE.BoxGeometry(doorWidth, doorHeight - 2 * frameThickness, frameThickness);
    const rightFrame = new THREE.Mesh(rightFrameGeo, frameMaterial);
    rightFrame.position.set(0, 1 - doorHeight / 2, doorDepth / 2 - frameThickness / 2);
    doorGroup.add(rightFrame);

    // 玻璃部分
    const glassHeight = doorHeight - 2 * frameThickness;
    const glassDepth = doorDepth - 2 * frameThickness;
    const glassMaterial = new THREE.MeshPhysicalMaterial({
        color: 0x88aaff,
        metalness: 0,
        roughness: 0,
        transmission: 1, // 物理透明
        transparent: true,
        opacity: 0.9,
        thickness: 0.01,
        clearcoat: 1,
        clearcoatRoughness: 0,
    });
    const glassGeo = new THREE.BoxGeometry(doorWidth - 0.01, glassHeight, glassDepth);
    const glass = new THREE.Mesh(glassGeo, glassMaterial);
    glass.position.set(0, 1 - doorHeight / 2, 0);
    doorGroup.add(glass);
    scene.add(doorGroup);
    //设置门的位置
    // 先设置门的位置和朝向
    doorGroup.position.set(0, 0.95, 0.3); // 调整位置到机柜前面
    doorGroup.rotation.y = Math.PI / 2; // 门朝向前面

    // 设置前门轴心为右下
    // 1. 创建一个pivot组作为轴心
    const pivot = new THREE.Group();
    //显示辅助框
    pivot.position.set(0.3, 0, doorDepth / 2); // 设置pivot位置为右下角
    //添加一个辅助球
    // 2. 将doorGroup移到pivot下，并调整doorGroup相对pivot的位置
    // 先把doorGroup的旋转和位置设置好，再做相对pivot的偏移
    doorGroup.position.sub(pivot.position); // doorGroup相对pivot的偏移
    pivot.add(doorGroup);

    // 3. 将pivot添加到场景
    scene.add(pivot);
    return pivot;
}


/**
 * 绘制后门（左右结构）
 * 门的高度和机柜高度一致，z正方向为前面，门的中间是通风空（无格子）
 * 左右两扇门对开
 * 返回 { group, leftDoor, rightDoor }
 */
export function createCabinetBackDoor(scene) {
    // 创建一个组来包含后门的所有部分
    const doorGroup = new THREE.Group();

    // 门的整体尺寸
    const doorWidth = 0.04;
    const doorHeight = 2;
    const doorDepth = 0.6;

    // 单扇门宽度（左右结构）
    const singleDoorDepth = doorDepth / 2;

    // 门框（上下边框+左右边框）
    const frameMaterial = materials.baseMaterial;
    const frameThickness = 0.04;

    // 创建单扇门的函数
    function createSingleBackDoor(isLeft) {
        const singleGroup = new THREE.Group();

        // 上边框
        const topFrameGeo = new THREE.BoxGeometry(doorWidth, frameThickness, singleDoorDepth);
        const topFrame = new THREE.Mesh(topFrameGeo, frameMaterial);
        topFrame.position.set(0, 1 - frameThickness / 2, 0);
        singleGroup.add(topFrame);

        // 下边框
        const bottomFrameGeo = new THREE.BoxGeometry(doorWidth, frameThickness, singleDoorDepth);
        const bottomFrame = new THREE.Mesh(bottomFrameGeo, frameMaterial);
        bottomFrame.position.set(0, -doorHeight / 2 + 0.05, 0);
        singleGroup.add(bottomFrame);

        // 外侧边框
        const sideFrameGeo = new THREE.BoxGeometry(doorWidth, doorHeight - 2 * frameThickness, frameThickness);
        const sideFrame = new THREE.Mesh(sideFrameGeo, frameMaterial);
        // 外侧在最外侧
        sideFrame.position.set(
            0,
            1 - doorHeight / 2,
            isLeft
                ? -singleDoorDepth / 2 + frameThickness / 2
                : singleDoorDepth / 2 - frameThickness / 2
        );
        singleGroup.add(sideFrame);

        // 内侧边框（中间对接处）
        const midFrameGeo = new THREE.BoxGeometry(doorWidth, doorHeight - 2 * frameThickness, frameThickness);
        const midFrame = new THREE.Mesh(midFrameGeo, frameMaterial);
        // 内侧在中间
        midFrame.position.set(
            0,
            1 - doorHeight / 2,
            isLeft
                ? singleDoorDepth / 2 - frameThickness / 2
                : -singleDoorDepth / 2 + frameThickness / 2
        );
        singleGroup.add(midFrame);
        // 创建通风孔
        // 创建通风孔贴图
        const ventTextureSize = 128;
        const ventCanvas = document.createElement('canvas');
        ventCanvas.width = ventCanvas.height = ventTextureSize;
        const ctx = ventCanvas.getContext('2d');
        ctx.fillStyle = '#ffffff';
        ctx.fillRect(0, 0, ventTextureSize, ventTextureSize);
        ctx.fillStyle = '#000000';
        const holeRadius = 6;
        const spacing = 20;
        for (let y = spacing / 2; y < ventTextureSize; y += spacing) {
            for (let x = spacing / 2; x < ventTextureSize; x += spacing) {
            ctx.beginPath();
            ctx.arc(x, y, holeRadius, 0, Math.PI * 2);
            ctx.fill();
            }
        }
        const ventTexture = new THREE.CanvasTexture(ventCanvas);
        ventTexture.wrapS = ventTexture.wrapT = THREE.RepeatWrapping;
        ventTexture.repeat.set(4, 16);

        // 通风孔材质
        const ventMaterial = new THREE.MeshStandardMaterial({
            color: 0xcccccc,
            metalness: 0.7,
            roughness: 0.5,
            alphaMap: ventTexture,
            transparent: true,
            side: THREE.DoubleSide,
        });

        const ventGeo = new THREE.BoxGeometry(doorWidth - 0.01, doorHeight - 2 * frameThickness, singleDoorDepth - 0.01);
        const vent = new THREE.Mesh(ventGeo, ventMaterial);
        vent.position.set(0, 1 - doorHeight / 2, 0);
        singleGroup.add(vent);
        // 设置单扇门的旋转方向
        return singleGroup;
    }

    // 左门
    const leftDoor = createSingleBackDoor(true);
    leftDoor.position.set(0.12, doorHeight/2 - 2* frameThickness, -doorDepth / 2); // 向右偏移
    leftDoor.rotation.y = Math.PI/2; // 右门需要旋转180度
    // 设置左门的旋转轴心
    const leftPivot = new THREE.Group();
    leftPivot.position.set(0.28, doorHeight / 2, -doorDepth / 2); // 设置左门的轴心位置
    leftDoor.position.sub(leftPivot.position); // 设置左门的轴心位置为左门的轴心位置
    leftPivot.add(leftDoor);
    scene.add(leftPivot);

    // 右门
    const rightDoor = createSingleBackDoor(false);
    rightDoor.position.set(-0.12, doorHeight/2 - 2* frameThickness, -doorDepth / 2); // 向右偏移
    rightDoor.rotation.y = Math.PI/2; // 右门需要旋转180度

     // 设置右门的旋转轴心
    const rightPivot = new THREE.Group();
    rightPivot.position.set(-0.28,  doorHeight / 2, -doorDepth/2); // 设置右门的轴心位置
    rightDoor.position.sub(rightPivot.position); // 设置右门的轴心位置为右门的轴心位置
    rightPivot.add(rightDoor);
    scene.add(rightPivot);

    // 返回组对象和左右门组
    return {leftDoor:leftPivot, rightDoor:rightPivot };
}


// 创建动画

function createAnimation(doorGroup, leftDoor, rightDoor) {
    document.getElementById('toggleDoorBtn').addEventListener('click', () => {
        // 使用GSAP对pivot进行旋转动画
        gsap.to(doorGroup.rotation, {
            y: doorGroup.rotation.y === 0 ? Math.PI / 2 : 0,
            duration: 1,
            ease: "power2.inOut"
        });
        // 使用GSAP对左右门进行开合动画
        gsap.to(leftDoor.rotation, {
            y: leftDoor.rotation.y === 0 ? -Math.PI / 2 : 0,
            duration: 1,
            ease: "power2.inOut"
        });
        gsap.to(rightDoor.rotation, {
            y: rightDoor.rotation.y === 0 ? Math.PI / 2 : 0,
            duration: 1,
            ease: "power2.inOut"
        });
    });
}

//执行开门
export function openDoors() {
    // 执行前门开门动画
    doorAnimation.clipAction(openDoorClip).play();
    // 执行后门开门动画
    doorAnimation.clipAction(openBackDoorLeft).play();
    doorAnimation.clipAction(openBackDoorRight).play();
}
